package com.mdoya.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdoya.domain.AddressBook;
import com.mdoya.exception.BusinessExceptiion;
import com.mdoya.response.ResultResponse;
import com.mdoya.service.AddressBookService;
import com.mdoya.utils.ThreadLocalContextUtils;
import com.sun.prism.impl.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址管理
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增地址簿
     */
    @PostMapping
    public ResultResponse<AddressBook> save(@RequestBody AddressBook addressBook) {
        addressBook.setUserId(ThreadLocalContextUtils.getUserLongId());
        log.info("addressBook:{}", addressBook);
        addressBookService.save(addressBook);
        return ResultResponse.success(addressBook);
    }

    /**
     * 设置默认地址
     */
    @PutMapping("default")
    public ResultResponse<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
        log.info("addressBook:{}", addressBook);
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, ThreadLocalContextUtils.getUserLongId());
        wrapper.set(AddressBook::getIsDefault, 0);
        //SQL:update address_book set is_default = 0 where user_id = ?
        addressBookService.update(wrapper);

        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
        addressBookService.updateById(addressBook);
        return ResultResponse.success(addressBook);
    }

    /**
     * 根据id查询地址
     */
    @GetMapping("/{id}")
    public ResultResponse get(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook != null) {
            return ResultResponse.success(addressBook);
        } else {
            return ResultResponse.error("没有找到该对象");
        }
    }

    /**
     * 查询默认地址
     */
    @GetMapping("default")
    public ResultResponse<AddressBook> getDefault() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, ThreadLocalContextUtils.getUserLongId());
        queryWrapper.eq(AddressBook::getIsDefault, 1);

        //SQL:select * from address_book where user_id = ? and is_default = 1
        AddressBook addressBook = addressBookService.getOne(queryWrapper);

        if (null == addressBook) {
            return ResultResponse.error("没有找到该对象");
        } else {
            return ResultResponse.success(addressBook);
        }
    }

    /**
     * 查询指定用户的全部地址
     */
    @GetMapping("/list")
    public ResultResponse<List<AddressBook>> list(AddressBook addressBook) {
        addressBook.setUserId(ThreadLocalContextUtils.getUserLongId());
        log.info("addressBook:{}", addressBook);

        //条件构造器
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);

        //SQL:select * from address_book where user_id = ? order by update_time desc
        return ResultResponse.success(addressBookService.list(queryWrapper));
    }

    /**
     *  根据用户删除对应地址簿
     * @param ids
     * @return
     */
    @DeleteMapping
    public ResultResponse deleteByid(Long ids) {
        log.info("删除地址簿: {}", ids);
        if (ids == null){
            throw new BusinessExceptiion(-1,"请选择地址簿");
        }
        Long userId = ThreadLocalContextUtils.getUserLongId();
        System.err.println("删除地址簿: {}" + ids + "    用户id：  " + userId);
        return ResultResponse.success(addressBookService.deleteByid(ids,userId) > 0 ? "删除地址簿成功" : "删除地址簿失败");
    }

    @PutMapping
    public ResultResponse updateById(@RequestBody AddressBook addressBook) {
        addressBook.setUserId(ThreadLocalContextUtils.getUserLongId());
        log.info("addressBook:{}", addressBook);
        return ResultResponse.success(addressBookService.updateById(addressBook) > 0 ? "更新成功" : "更新失败");
    }
}
